<template>
	<div style="background-color: white;">
		<div class="export"><a-button type="primary" class="m-5" @click="printElement('visa-info-page')">打印/导出PDF</a-button></div>
		<div v-if="formState.visa_date_type === 0" id="visa-info-page">
			<div class="tab-page">
				<a-row>
					<a-col :span="24" class="text-center">零星用工签证单</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">完成时间</a-col>
					<a-col :span="8">{{ formState.visa_date }}</a-col>
					<a-col :span="4">编号</a-col>
					<a-col :span="8">{{ formState.code }}</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">项目名称</a-col>
					<a-col :span="8">{{ supplyOrderInfo.project?.name }}</a-col>
					<a-col :span="4">完成单位</a-col>
					<a-col :span="8">{{ supplyOrderInfo.supplier?.company_name }}</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">零星用工类型</a-col>
					<a-col :span="8">{{ `${supplyOrderInfo.materials?.[0]?.name}/${supplyOrderInfo.materials?.[0]?.model}/${supplyOrderInfo.materials?.[0]?.unit}` }}</a-col>
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 施工阶段</a-col>
					<a-col :span="8">
						<span>{{ buildPhaseList?.find(item => item.id === formState.build_phase)?.name }}</span>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 工作事由</a-col>
					<a-col :span="8">
						<span v-if="formState.id">{{ workSourceList?.find(item => item.id === formState.work_source_id)?.name }}</span>
						<a-select v-else v-model:value="formState.work_source_id" style="width: 100%" placeholder="请选择工作事由" :options="workSourceList" option-filter-prop="label" :disabled="!canEditFormInfo"></a-select>
					</a-col>
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 工作部位</a-col>
					<a-col :span="8">
						<span v-if="formState.id">{{ formState.gonghao_name }}</span>
						<a-tree-select v-else v-model:value="formState.gonghao_id" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" :disabled="!canEditFormInfo">
							<template #title="{ label }">{{ label }}</template>
						</a-tree-select>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">详细工作内容</a-col>
					<a-col :span="20">
						<span v-if="formState.id">{{ formState.detail_remark }}</span>
						<a-textarea v-else v-model:value="formState.detail_remark" :auto-size="{ minRows: 5}" :disabled="!canEditFormInfo" />
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="4" class="text-center"><a-typography-text type="danger">*</a-typography-text> 作业时间</a-col>
					<a-col :span="20" class="parent-col-not-h-full text-center">
						<template v-for="(item, index) in formState.work_time_list" :key="index">
							<a-row v-if="item.type === 'dayShift'">
								<a-col :span="2" class="text-center">白班</a-col>
								<a-col :span="8">
									<div v-if="formState.id">{{ item.work_range.length ?(dayjs(item.work_range[0]).format('YYYY-MM-DD HH:mm') + ' ~ ' + dayjs(item.work_range[1]).format('YYYY-MM-DD HH:mm')) : '' }}</div>
									<a-range-picker
										v-else
										v-model:value="item.work_range"
										:disabled-date="current => disabledDate(item, current)"
										:disabled-time="(current, type = 'start' | 'end') => disabledTime(item, current, type)"
										:show-time="{
											hideDisabledOptions: true,
											defaultValue: [dayjs('06:00', 'HH:mm'), dayjs('18:00', 'HH:mm')],
										}"
										format="YYYY-MM-DD HH:mm"
										@calendarChange="val => onCalendarChange(item, val)"
										@change="changeWorkRange"
									/>
								</a-col>
								<a-col :span="2" style="border-left: 0;"> {{ (item.work_range?.length === 2 ? (dayjs(item.work_range[1]).diff(item.work_range[0], 'hours', true) / 9).toFixed(2) : '0') + '工日' }}</a-col>
								<a-col :span="5">上传图片</a-col>
								<a-col :span="7">
									<a-button v-if="canEditFormInfo" type="link" @click="toUpload(item)">
										<span v-if="!item.files?.length">上传</span>
										<span v-else>继续上传</span>
									</a-button>
									<template v-else>
										<a-button v-if="item.files?.length" type="link" @click="toUpload(item)">
											<span>查看</span>
										</a-button>
										<a-typography-text v-else type="danger" style="font-size: .8rem">暂无</a-typography-text>
									</template>
								</a-col>
							</a-row>
							<a-row v-else-if="item.type === 'nightShift'">
								<a-col :span="2">夜班</a-col>
								<a-col :span="8">
									<div v-if="formState.id">{{ item.work_range.length ?(dayjs(item.work_range[0]).format('YYYY-MM-DD HH:mm') + ' ~ ' + dayjs(item.work_range[1]).format('YYYY-MM-DD HH:mm')) : '' }}</div>
									<a-range-picker
										v-else
										v-model:value="item.work_range"
										:disabled-date="current => disabledDate(item, current)"
										:disabled-time="(current, type = 'start' | 'end') => disabledTime(item, current, type)"
										:show-time="{
											hideDisabledOptions: true,
											defaultValue: [dayjs('18:00', 'HH:mm'), dayjs('06:00', 'HH:mm')],
										}"
										format="YYYY-MM-DD HH:mm"
										@calendarChange="val => onCalendarChange(item, val)"
										@change="changeWorkRange"
									/>
								</a-col>
								<a-col :span="2" style="border-left: 0;">{{ (item.work_range?.length === 2 ? (dayjs(item.work_range[1]).diff(item.work_range[0], 'hours', true) / 6).toFixed(2) : '0') + '工日' }}</a-col>
								<a-col :span="5">上传图片</a-col>
								<a-col :span="7">
									<a-button v-if="canEditFormInfo" type="link" @click="toUpload(item)">
										<span v-if="!item.files?.length">上传</span>
										<span v-else>继续上传</span>
									</a-button>
									<template v-else>
										<a-button v-if="item.files?.length" type="link" @click="toUpload(item)">
											<span>查看</span>
										</a-button>
										<a-typography-text v-else type="danger" style="font-size: .8rem">暂无</a-typography-text>
									</template>
								</a-col>
							</a-row>
						</template>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="4" class="text-center"><a-typography-text type="danger">*</a-typography-text> 累计完成时间</a-col>
					<a-col :span="20">
						<span v-if="formState.id" class="pl-5">{{ formState.work_hours + ' (工日)' }}</span>
						<a-input-number v-else v-model:value="formState.work_hours" style="width: 100%;" :min="0" :max="Math.min(maxUseTime, 20)" :step="0.5" :disabled="!canEditFormInfo">
							<template v-if="formState.work_hours" #addonAfter>工日</template>
						</a-input-number>
						<div style="color:red;font-size: .6rem" class="mt-1">累计完成时间为当天一次性录入，不能二次修改，请谨慎操作。</div>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">使用人确认</a-col>
					<a-col :span="8" style="font-size: .8rem">
						<span v-if="formState.id">
							<img v-if="formState.opr.manually_signed_file_path" :src="formState.opr.manually_signed_file_path" height="30" />
							<span v-else>{{ formState.opr.fullname }}</span>
							<span>/ {{ formState.create_time }}</span>
						</span>
					</a-col>
					<a-col :span="4">完成单位确认</a-col>
					<a-col :span="8">
						<span v-if="formState.id && formState.visa_status !== 0" style="font-size: .8rem">
							<img v-if="formState.supplier?.manually_signed_file_path" :src="formState.supplier?.manually_signed_file_path" height="30" />
							<span v-else>{{ formState.opr.fullname }}</span>
							{{ ' / ' + formState.supplier_sign_time }}
						</span>
						<a-popconfirm
							v-else
							title="是否确定签名该数据?"
							ok-text="确定"
							cancel-text="取消"
							@confirm="supplierSign(formState)"
						>
							<a-button v-permission="224" type="primary" :disabled="!(formState.id && formState.visa_status === 0)">确认</a-button>
						</a-popconfirm>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 出工单位</a-col>
					<a-col :span="20">
						<span v-if="formState.id">{{ providerList?.find(item => item.value === formState.provider_id)?.label }}</span>
						<a-select v-else v-model:value="formState.provider_id" style="width: 100%" placeholder="请选择出工单位" :options="providerList" option-filter-prop="label" :disabled="!canEditFormInfo"></a-select>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">商务部人员</a-col>
					<a-col :span="8">
						<span v-if="formState.id && supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 1)?.status === 1" style="font-size: .8rem">
							<img v-if="supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 1)?.auditor?.manually_signed_file_path" :src="supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 1)?.auditor?.manually_signed_file_path" height="30" />
							<span v-else>{{ supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 1)?.auditor?.fullname }}</span>
							{{ ' / ' + supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 1)?.audited_time }}</span>
						<a-popconfirm
							v-else
							title="是否确定签名该数据?"
							ok-text="确定"
							cancel-text="取消"
							@confirm="auditSign({batch: formState.batch, code: formState.code}, 1)"
						>
							<a-button v-permission="225" type="primary" :disabled="!(formState.id && [1,2].includes(formState.visa_status))">确认</a-button>
						</a-popconfirm>
					</a-col>
					<a-col :span="4">生产经理/项目总工</a-col>
					<a-col :span="8">
						<span v-if="formState.id && supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 2)?.status === 1" style="font-size: .8rem">
							<img v-if="supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 2)?.auditor?.manually_signed_file_path" :src="supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 2)?.auditor?.manually_signed_file_path" height="30" />
							<span v-else>{{ supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 2)?.auditor?.fullname }}</span>
							{{ ' / ' + supplyOrderInfo?.visaAuditLogs.find(item => item.auditor_type === 2)?.audited_time }}</span>
						<a-popconfirm
							v-else
							title="是否确定签名该数据?"
							ok-text="确定"
							cancel-text="取消"
							@confirm="auditSign({batch: formState.batch, code: formState.code}, 2)"
						>
							<a-button v-permission="226" type="primary" :disabled="!(formState.id && [1,2].includes(formState.visa_status))">确认</a-button>
						</a-popconfirm>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">备注</a-col>
					<a-col :span="20">
						<span v-if="formState.id">{{ formState.remark }}</span>
						<a-textarea v-else v-model:value="formState.remark" :auto-size="{ minRows: 3}" :disabled="!canEditFormInfo" />
					</a-col>
				</a-row>
			</div>
			<div class="text-center mt-5">
				<a-button @click="back">返回</a-button>
				<a-button v-if="canEditFormInfo" v-permission="223" type="primary" class="ml-10" :loading="beingSubmitted" @click="saveHour">确认</a-button>
			</div>
			<br />
		</div>
		<div v-else id="visa-info-page">
			<div class="tab-page">
				<a-row>
					<a-col :span="24" class="text-center">租赁设备运转记录表</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="4">项目名称</a-col>
					<a-col :span="8">{{ supplyOrderInfo.project?.name }}</a-col>
					<a-col :span="4">验收单编号</a-col>
					<a-col :span="8">{{ supplyOrderInfo.yanshouLog?.code }}</a-col>
				</a-row>
				<a-row>
					<a-col :span="24" class="text-center">一、设备基本信息</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">设备名称</a-col>
					<a-col :span="5">设备型号规格</a-col>
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 设备编号</a-col>
					<a-col :span="4"><a-typography-text type="danger">*</a-typography-text> 设备牌照</a-col>
					<a-col :span="6">设备租赁供方名称</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">{{ supplyOrderInfo.materials?.[0]?.name }}</a-col>
					<a-col :span="5">{{ supplyOrderInfo.materials?.[0]?.model }}</a-col>
					<a-col :span="4">
						<a-input v-model:value="formStateMonth.material_no" placeholder="请输入设备编号" />
					</a-col>
					<a-col :span="4">
						<a-input v-model:value="formStateMonth.material_license_plate" placeholder="请输入设备牌照" />
					</a-col>
					<a-col :span="6">{{ supplyOrderInfo.supplier?.company_name }}</a-col>
				</a-row>
				<a-row>
					<a-col :span="24" class="text-center">二、设备运转记录</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5" class="parent-col">
						<a-row>
							<a-col :span="10">
								<tempalte v-if="batch">
									<span>{{ dayjs(formStateMonth.records.find(item => item.batch === batch)?.visa_date).format('YYYY年MM月') }}</span>
								</tempalte>
								<tempalte v-else>
									<span v-if="dayjs().date() <=3">{{ dayjs().format('YYYY年') }}</span>
									<span v-else>{{ dayjs().format('YYYY年MM月') }}</span>
								</tempalte>
							</a-col>
							<a-col :span="14"><a-typography-text type="danger">*</a-typography-text> 开始时间</a-col>
						</a-row>
					</a-col>
					<a-col :span="5" class="parent-col">
						<a-row>
							<a-col :span="14"><a-typography-text type="danger">*</a-typography-text> 结束时间</a-col>
							<a-col :span="10"><a-typography-text type="danger">*</a-typography-text> 运转时间（h）</a-col>
						</a-row>
					</a-col>
					<a-col :span="4" class="parent-col">
						<a-row>
							<a-col :span="12">完成工作量</a-col>
							<a-col :span="12">主要工作</a-col>
						</a-row>
					</a-col>
					<a-col :span="4" class="parent-col">
						<a-row>
							<a-col :span="12"><a-typography-text type="danger">*</a-typography-text> 施工工号</a-col>
							<a-col :span="12"><a-typography-text type="danger">*</a-typography-text> 添加燃油（L）</a-col>
						</a-row>
					</a-col>
					<a-col :span="6" class="parent-col">
						<a-row>
							<a-col :span="8">设备租赁供方签认</a-col>
							<a-col :span="8">分包单位（如有）</a-col>
							<a-col :span="8">项目签认</a-col>
						</a-row>
					</a-col>
				</a-row>
				<a-row v-for="(item, index) in formStateMonth.records" :key="index" class="text-center">
					<a-col :span="5" class="parent-col">
						<a-row style="height: 100%;">
							<a-col :span="10">
								<span v-if="!recordDisabled(item)">
									<a-typography-text type="success">
										{{ dayjs().date() <=3?dayjs(item.visa_date).format('MM月DD日') : dayjs(item.visa_date).format('DD日') }}
									</a-typography-text>
								</span>
								<span v-else>{{ dayjs().date() <=3?dayjs(item.visa_date).format('MM月DD日') : dayjs(item.visa_date).format('DD日') }}</span>
							</a-col>
							<a-col :span="14">
								<div v-if="item.id">{{ dayjs(item.start_time).format('HH:mm') }}</div>
								<a-time-picker v-else v-model:value="item.start_time" format="HH:mm" :disabled="recordDisabled(item)" @change="changeMonthTime(item)" />
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="5" class="parent-col">
						<a-row>
							<a-col :span="14">
								<div v-if="item.id">{{ dayjs(item.end_time).format('HH:mm') }}</div>
								<a-time-picker v-else v-model:value="item.end_time" format="HH:mm" :disabled="recordDisabled(item)" @change="changeMonthTime(item)" />
							</a-col>
							<a-col :span="10">
								<div v-if="item.id">{{ item.work_hours }}</div>
								<a-input-number v-else v-model:value="item.work_hours" :min="0.01" :max="24" :precision="2" style="width: 100%" placeholder="运作时间" :disabled="recordDisabled(item)" />
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="4" class="parent-col">
						<a-row>
							<a-col :span="12">
								<div v-if="item.id">{{ item.workload }}</div>
								<a-input v-else v-model:value="item.workload" style="width: 100%" placeholder="工作量" :disabled="recordDisabled(item)" />
							</a-col>
							<a-col :span="12">
								<div v-if="item.id">{{ item.main_work }}</div>
								<a-input v-else v-model:value="item.main_work" style="width: 100%" placeholder="主要工作" :disabled="recordDisabled(item)" />
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="4" class="parent-col">
						<a-row>
							<a-col :span="12">
								<div v-if="item.id" style="font-size: .8rem">{{ item.gonghao_name }}</div>
								<a-tree-select v-else v-model:value="item.gonghao_id" :dropdown-match-select-width="false" :show-search="true" placeholder="工号" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" :disabled="recordDisabled(item)">
									<template #title="{ label }">{{ label }}</template>
								</a-tree-select>
							</a-col>
							<a-col :span="12">
								<div v-if="item.id">{{ item.fuel_oil }}</div>
								<a-input-number v-else v-model:value="item.fuel_oil" :min="0" :precision="2" :max="100" placeholder="燃油(L)" style="width: 100%" :disabled="recordDisabled(item)" />
							</a-col>
						</a-row>
					</a-col>
					<a-col :span="6" class="parent-col">
						<a-row style="height: 100%;">
							<a-col :span="8">
								<span v-if="item.id && item.visa_status !== 0" style="font-size: .8rem">
									<img v-if="item.supplier.manually_signed_file_path" :src="item.supplier.manually_signed_file_path" height="30" />
									<span v-else>{{ item.supplier.fullname }}</span>
								</span>
								<a-popconfirm
									v-else
									title="是否确定签名该数据?"
									ok-text="确定"
									cancel-text="取消"
									@confirm="supplierSign(item)"
								>
									<a-button v-permission="227" type="primary" :disabled="!(item.id && item.visa_status === 0)">确认</a-button>
								</a-popconfirm>
							</a-col>
							<a-col :span="8">
								<div v-if="item.id" style="font-size: .7rem">{{ providerList.find(i => i.value == item.provider_id)?.label }}</div>
								<a-select v-else v-model:value="item.provider_id" style="width: 100%" placeholder="分包单位" :options="providerList" option-filter-prop="label" :disabled="recordDisabled(item)"></a-select>
							</a-col>
							<a-col :span="8">
								<a-popconfirm
									v-if="!item.id"
									title="提交后不可修改, 确定要提交吗?"
									ok-text="确定"
									cancel-text="取消"
									@confirm="saveMonth(item)"
								>
									<a-button v-permission="223" type="primary" :loading="item.beingSubmitted" :disabled="recordDisabled(item)">确认</a-button>
								</a-popconfirm>
								<template v-else>
									<img v-if="item.opr.manually_signed_file_path" :src="item.opr.manually_signed_file_path" height="30" />
									<span v-else>{{ item.opr.fullname }}</span>
								</template>
							</a-col>
						</a-row>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">合计</a-col>
					<a-col v-if="batch" :span="7">
						<template v-for="(item, index) in [add(formStateMonth.records.filter(i => i.work_hours > 0 && i.batch === batch).map(i => i.work_hours))]" :key="index">
							{{ item + ' (' + parseInt(item) + '小时' + parseInt(item % 1 * 60) + '分) ' }}
						</template>
					</a-col>
					<a-col v-else :span="7">
						<template v-for="(item, index) in [add(formStateMonth.records.filter(i => i.work_hours > 0 && dayjs(i.visa_date).format('YYYY-MM') === dayjs().format('YYYY-MM')).map(i => i.work_hours))]" :key="index">
							{{ item + ' (' + parseInt(item) + '小时' + parseInt(item % 1 * 60) + '分) ' }}
						</template>
					</a-col>
					<a-col :span="6">燃油合计</a-col>
					<a-col v-if="batch" :span="6">
						<teamplate v-for="(item, index) in [add(formStateMonth.records.filter(i => i.fuel_oil > 0 && i.batch === batch).map(i => i.fuel_oil))]" :key="index">
							{{ item }}
						</teamplate>
					</a-col>
					<a-col v-else :span="6">
						<template v-for="(item, index) in [add(formStateMonth.records.filter(i => i.fuel_oil > 0 && dayjs(i.visa_date).format('YYYY-MM') === dayjs().format('YYYY-MM')).map(i => i.fuel_oil))]" :key="index">
							{{ item }}
						</template>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">项目总工审核意见</a-col>
					<a-col :span="19">
						<span v-if="supplyOrderInfo?.visaAuditLogs?.find(i => i.auditor_type === 1 && i.status === 1 && i.code === formStateMonth?.code)">
							<template v-for="(item, index) in supplyOrderInfo?.visaAuditLogs?.filter(i => i.auditor_type === 1 && i.status === 1 && i.code === formStateMonth?.code)" :key="index">
								<span v-if="item.remark">审核意见：{{ item.remark }}<br /></span>
								<img v-if="item.auditor?.manually_signed_file_path" :src="item.auditor?.manually_signed_file_path" height="30" />
								<span v-else>{{ item.auditor?.fullname }}</span>
								{{ ' / ' + item?.audited_time }}
							</template>
						</span>
						<a-button v-else v-permission="229" type="primary" :disabled="!canAudit()" @click="openAuditModel(1)">确认</a-button>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">项目工程技术部经办人审核意见</a-col>
					<a-col :span="19">
						<span v-if="supplyOrderInfo?.visaAuditLogs?.find(i => i.auditor_type === 2 && i.status === 1 && i.code === formStateMonth?.code)">
							<template v-for="(item, index) in supplyOrderInfo?.visaAuditLogs?.filter(i => i.auditor_type === 2 && i.status === 1 && i.code === formStateMonth?.code)" :key="index">
								<span v-if="item.remark">审核意见：{{ item.remark }}<br /></span>
								<img v-if="item.auditor?.manually_signed_file_path" :src="item.auditor?.manually_signed_file_path" height="30" />
								<span v-else>{{ item.auditor?.fullname }}</span>
								{{ ' / ' + item?.audited_time }}
							</template>
						</span>
						<a-button v-else v-permission="230" type="primary" :disabled="!canAudit()" @click="openAuditModel(2)">确认</a-button>
					</a-col>
				</a-row>
				<a-row class="text-center">
					<a-col :span="5">项目工程技术部负责人<br />审核意见</a-col>
					<a-col :span="19">
						<span v-if="supplyOrderInfo?.visaAuditLogs?.find(i => i.auditor_type === 3 && i.status === 1 && i.code === formStateMonth?.code)">
							<template v-for="(item, index) in supplyOrderInfo?.visaAuditLogs?.filter(i => i.auditor_type === 3 && i.status === 1 && i.code === formStateMonth?.code)" :key="index">
								<span v-if="item.remark">{{ item.remark }}<br /></span>
								<img v-if="item.auditor?.manually_signed_file_path" :src="item.auditor?.manually_signed_file_path" height="30" />
								<span v-else>{{ item.auditor?.fullname }}</span>
								{{ ' / ' + item?.audited_time }}
							</template>
						</span>
						<a-button v-else v-permission="231" type="primary" :disabled="!canAudit()" @click="openAuditModel(3)">确认</a-button>
					</a-col>
				</a-row>
			</div>
			<div class="text-center mt-5">
				<a-button @click="back">返回</a-button>
			</div>
			<br />
		</div>
		<a-modal v-model:visible="img_upload_ref.img_visible" :width="400" title="上传图片" :ok-button-props="{ disabled: !canEditFormInfo, loading: img_upload_ref.uploading }" @ok="saveFileList">
			<a-upload v-model:file-list="img_upload_ref.files" list-type="picture" name="upload" :action="`${baseURL}/contract/upload`" :headers="{Authorization:`Bearer ${proxy.$cookies.get('token')}`}" accept="image/*" :disabled="!canEditFormInfo" :before-upload="() => img_upload_ref.uploading = true" @change="changeImgUpload" @remove="removeFile">
				<a-button>
					<template v-if="img_upload_ref.uploading">
						<loading-outlined />上传图片中...
					</template>
					<template v-else>
						<import-outlined />上传图片
					</template>
				</a-button>
			</a-upload>
		</a-modal>
		<a-modal v-model:visible="auditModel.visible" :width="400" title="审核意见" :ok-button-props="{ loading: auditModel.uploading }" @ok="auditSign(auditModel.data, auditModel.data.auditor_type, formState.visa_date_type)">
			<a-textarea v-model:value="auditModel.data.remark" :auto-size="{ minRows: 5}" />
		</a-modal>
	</div>
</template>
<script setup>
import dayjs from "dayjs";
import { ref, onMounted, computed, h, getCurrentInstance, reactive, inject } from "vue";
import { post, postJson } from "@/utils/index.js";
import { useRoute, useRouter } from "vue-router";
import { Modal } from 'ant-design-vue';
import { baseURL } from "@/utils/request.js";
const { proxy } = getCurrentInstance();
import { ImportOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { userStore } from "../store";
import { add } from '../utils/operation.js'
import { printElement } from "@/utils/exportData.js";
const formState = ref({});
const formStateMonth = ref({
	records: [],
});
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const batch = computed(() => {
	return route.query.batch || 0;
});
const router = useRouter();
const store = userStore();
const userInfo = store.info;
// 是否有信息录入
const canEditFormInfo = ref(false);
const disabledDate = (item, current) => {
	if (!item.calendar_range || !item.calendar_range[0]) return false;
	if (item.type === 'dayShift') {
		return current.diff(item.calendar_range[0], 'day') >= 1;
	} else {
		return current.diff(item.calendar_range[0], 'day', true) > 1;
	}
}
const disabledTime = (item, current, type) => {
	const range = (start, end) => {
		const arr = [];
		for (let i = start; i < end; i++) {
			arr.push(i);
		}
		return arr;
	};
	if (item.type === 'dayShift') {
		return {
			disabledHours: () => [...range(0, 6), ...range(19, 24)]
		};
	} else {
		if (type === 'start') {
			return {
				disabledHours: () => range(0, 18),
			};
		}
		return {
			disabledHours: () => range(7, 24),
		};
	}
}
const onCalendarChange = (item, val) => {
	item.calendar_range = val;
}
// 施工阶段
const buildPhaseList = ref([]);
// 工作事由
const workSourceList = ref([]);
const gonghaoTree = ref([]);
const providerList = ref([]);
const maxUseTime = ref(0);
const supplyOrderInfo = ref({});
const beingSubmitted = ref(false);
post("dictionary", { root_id: 1288 }).then(data => {
	buildPhaseList.value = data;
});
post("dictionary", { root_id: 1289 }).then(data => {
	workSourceList.value = data;
});

const img_upload_ref = reactive({
	img_visible: false,
	uploading: false,
	files: [],
});
const auditModel = reactive({
	visible: false,
	uploading: false,
	data: {},
})
onMounted(async () => {
	supplyOrderInfo.value = await post(`supplyOrder/info`, { id: id.value });
	if (supplyOrderInfo.value.ys_settings?.find(item => item.opr_type === 1 && item.opr_id === userInfo.id)) {
		canEditFormInfo.value = true;
	} else if (!supplyOrderInfo.value.ys_settings.length && supplyOrderInfo.value.yanshouLog.opr_id === userInfo.id) {
		canEditFormInfo.value = true;
	}
	if (supplyOrderInfo.value.ys_type !== 7) {
		Modal.error({
			title: '数据异常',
			content: h('div', {}, [
				h('p', '当前单据类型不是零星用工,无法进行签证'),
			]),
			onOk() {
				router.push(`/yanshou/visalx`);
			},
		});
		return;
	}
	gonghaoTree.value = await post("department/getTrees", { type: 4, parent_id: supplyOrderInfo.value.project_id })
	maxUseTime.value = parseInt(supplyOrderInfo.value.materials?.[0]?.SupplyOrderMaterial?.quantity || '0');
	post("visa/provider", { project_id: supplyOrderInfo.value.project_id }).then(data => {
		providerList.value = data.map(item => {
			return {
				label: item.company_name,
				value: item.id,
			}
		});
	});
	post("aFewEmploy/info", { id: supplyOrderInfo.value.purchaseOrder?.apply_plan_id }).then(data => {
		formState.value.build_phase = data.build_phase;
	});
	formState.value.visa_date_type = 0;
	if (formState.value.visa_date_type === 0) {
		await formatFormStateHour();
	} else {
		await formatFormStateMonth();
	}
})
const initPage = async () => {
	supplyOrderInfo.value = await post(`supplyOrder/info`, { id: id.value });
	if (supplyOrderInfo.value.ys_settings?.find(item => item.opr_type === 1 && item.opr_id === userInfo.id)) {
		canEditFormInfo.value = true;
	}
	formState.value.visa_date_type = 0;
	if (formState.value.visa_date_type === 0) {
		await formatFormStateHour();
	} else {
		await formatFormStateMonth();
	}
}
const formatFormStateHour = async () => {
	if (batch.value && supplyOrderInfo.value.visaLogs?.length) {
		const _data = supplyOrderInfo.value.visaLogs.find(item => item.batch === batch.value);
		formState.value = _data ? _data : supplyOrderInfo.value.visaLogs.find(item => item.batch === batch.value);
	} else if (supplyOrderInfo.value.visaLogs?.length) {
		formState.value = supplyOrderInfo.value.visaLogs[0];
	}
	if (formState.value.id) {
		canEditFormInfo.value = false;
		formState.value.work_time_list = JSON.parse(formState.value.work_time_list).map(item => {
			if (item.work_range[0])item.work_range[0] = dayjs(dayjs(item.work_range[0]).format('YYYY-MM-DD HH:mm'), 'YYYY-MM-DD HH:mm');
			if (item.work_range[1])item.work_range[1] = dayjs(dayjs(item.work_range[1]).format('YYYY-MM-DD HH:mm'), 'YYYY-MM-DD HH:mm');
			return item;
		})
		formState.value.gonghao_name = recursionTreeName(gonghaoTree.value, formState.value.gonghao_id);
		formState.value.gonghao_id = gonghaoTree.value[0].parent_id + '-' + recursionTree(gonghaoTree.value, formState.value.gonghao_id, '')
		return;
	}
	formState.value.visa_date = dayjs().format('YYYY-MM-DD');
	const { code } = await postJson('visa/code', { supply_order_id: id.value, visa_date_type: 0, visa_date: formState.value.visa_date });
	formState.value.code = code;
	formState.value.supply_order_id = id.value;
	formState.value.work_time_list = [
		{ type: 'dayShift', work_range: [], calendar_range: [], files: [] },
		{ type: 'nightShift', work_range: [], calendar_range: [], files: [] },
	];
}
const recursionTree = (list, targetId, result) => {
	for (const item of list || []) {
		if (item.id === targetId) {
			if (!result) result += item.id;
			else result += '-' + item.id
			break;
		} else {
			const _result = recursionTree(item.children, targetId, result);
			if (_result !== result) {
				result = item.id + '-' + _result;
				return result;
			}
		}
	}
	return result;
}
const recursionTreeName = (list, targetId) => {
	for (const item of list || []) {
		if (item.id === targetId) {
			return item.label
		} else {
			const _result = recursionTreeName(item.children, targetId);
			if (_result) return _result;
		}
	}
}
const formatFormStateMonth = async () => {
	formStateMonth.value.material_no = supplyOrderInfo.value.materials?.[0]?.SupplyOrderMaterial.material_no;
	formStateMonth.value.material_license_plate = supplyOrderInfo.value.materials?.[0]?.SupplyOrderMaterial.material_license_plate;
	formStateMonth.value.records = [];
	formStateMonth.value.visa_date_type = 1;
	// 记录每个月的审核状态
	formStateMonth.value.month_visa_state = {};
	let _visa_date = dayjs(new Date()).format('YYYY-MM-DD');
	if (batch.value) {
		const _data = supplyOrderInfo.value.visaLogs.find(item => item.batch === batch.value);
		_visa_date = _data.visa_date;
		formStateMonth.value.code = _data.code;
	} else {
		const { code } = await postJson('visa/code', { supply_order_id: id.value, visa_date_type: 1 });
		formStateMonth.value.code = code;
	}
	const visaLogs2VisaDate = supplyOrderInfo.value.visaLogs.reduce((target, item) => {
		target[item.visa_date] = item;
		return target;
	}, {});
	if (dayjs().format('YYYY-MM') === dayjs(_visa_date).format('YYYY-MM')) {
		for (let i = 3; i > 0; i--) {
			if (dayjs().subtract(i, 'day').month() === dayjs().month()) break;
			// 上个月的记录已经审核了
			if ([2, 3].includes(supplyOrderInfo.value.visaLogs.find(item => dayjs(item.visa_date).format('YYYY-MM') === dayjs().subtract(i, 'day').format('YYYY-MM'))?.visa_status)) {
				break;
			}
			const _date = dayjs().subtract(i, 'day').format('YYYY-MM-DD');
			const _item = visaLogs2VisaDate[_date];
			if (_item) {
				const _month = dayjs(_date).format('YYYY-MM');
				if (!formStateMonth.value.month_visa_state[_month]) {
					formStateMonth.value.month_visa_state[_month] = _item.visa_status;
				}
				const workTimeList = JSON.parse(_item.work_time_list);
				_item.start_time = dayjs(dayjs(workTimeList[0].work_range[0]).format('HH:mm'), 'HH:mm');
				_item.end_time = dayjs(dayjs(workTimeList[0].work_range[1]).format('HH:mm'), 'HH:mm');
				_item.gonghao_name = recursionTreeName(gonghaoTree.value, _item.gonghao_id);
				_item.gonghao_id = gonghaoTree.value[0].parent_id + '-' + recursionTree(gonghaoTree.value, _item.gonghao_id, '')
				formStateMonth.value.records.push(_item)
			} else {
				formStateMonth.value.records.push({
					visa_date: _date,
					start_time: null,
					end_time: null,
					beingSubmitted: false,
				})
			}
		}
	}
	
	const startDate = dayjs(_visa_date).startOf('month').format('YYYY-MM-DD');
	const endDate = dayjs(_visa_date).endOf('month').format('YYYY-MM-DD');
	for (let date = startDate; date <= endDate; date = dayjs(date).add(1, 'day').format('YYYY-MM-DD')) {
		const _date = dayjs(date).format('YYYY-MM-DD');
		const _item = visaLogs2VisaDate[_date]
		if (_item) {
			const _month = dayjs(_date).format('YYYY-MM');
			if (!formStateMonth.value.month_visa_state[_month]) {
				formStateMonth.value.month_visa_state[_month] = _item.visa_status;
			}
			const workTimeList = JSON.parse(_item.work_time_list);
			_item.start_time = dayjs(dayjs(workTimeList[0].work_range[0]).format('HH:mm'), 'HH:mm');
			_item.end_time = dayjs(dayjs(workTimeList[0].work_range[1]).format('HH:mm'), 'HH:mm');
			_item.gonghao_name = recursionTreeName(gonghaoTree.value, _item.gonghao_id);
			_item.gonghao_id = gonghaoTree.value[0].parent_id + '-' + recursionTree(gonghaoTree.value, _item.gonghao_id, '')
			formStateMonth.value.records.push(_item)
		} else {
			formStateMonth.value.records.push({
				visa_date: _date,
			})
		}
	}
}
const changeMonthTime = (item) => {
	if (!item.start_time || !item.end_time) return;
	if (item.start_time.$d > item.end_time.$d) {
		const _time = item.end_time;
		item.end_time = item.start_time;
		item.start_time = _time;
	}
	const diffMinute = dayjs(item.end_time.$d).diff(dayjs(item.start_time.$d), 'minute');
	item.work_hours = add([0, diffMinute / 60], 2);
}

const recordDisabled = (item) => {
	const _date = dayjs(item.visa_date).format('YYYY-MM-DD');
	const _month = dayjs(_date).format('YYYY-MM');
	if (formStateMonth.value.month_visa_state[_month] && [2, 3].includes(formStateMonth.value.month_visa_state[_month])) return true;
	return !!(dayjs().subtract(3, 'day').format('YYYY-MM-DD') > _date ||
      dayjs().format('YYYY-MM-DD') < _date || item.id) || !canEditFormInfo.value;
}
// 改变工作时长
const changeWorkRange = () => {
	let workHours = 0;
	for (const item of formState.value.work_time_list) {
		if (item.work_range[0] && item.work_range[1]) {
			const diffHours = dayjs(item.work_range[1].$d).diff(dayjs(item.work_range[0].$d), 'hours', true);
			if (item.type === 'dayShift') {
				workHours = add([workHours, diffHours / 9], 2)
			} else {
				workHours = add([workHours, diffHours / 6], 2)
			}
		}
	}
	formState.value.work_hours = workHours;
}

const toUpload = (record) => {
	img_upload_ref.uploading = false;
	img_upload_ref.files = record.files.map(item => item);
	img_upload_ref.img_visible = true;
	img_upload_ref.source = record;
}
const changeImgUpload = ({ file }) => {
	if (file.status === "done") {
		img_upload_ref.files.push({
			uid: file.uid,
			name: file.name,
			url: file.response.data.url,
		});
		img_upload_ref.uploading = false;
		img_upload_ref.files = img_upload_ref.files.filter((item) => item.url)
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		img_upload_ref.files = img_upload_ref.files.filter((item) => item.url)
	}
};
const removeFile = (data) => {
	img_upload_ref.files = img_upload_ref.files.filter((item) => data.uid !== item.uid)
	return true;
}
const saveFileList = () => {
	img_upload_ref.source.files = img_upload_ref.files;
	img_upload_ref.img_visible = false;
	img_upload_ref.files = [];
}

const supplierSign = (item) => {
	const data = {
		visa_id: item.id,
	}
	postJson('visa/supplier/sign', data).then(data => {
		proxy.$message.success("签名成功", 1);
		initPage()
	}).catch(err => {
		proxy.$message.error(err);
	});
}
// 审核签名
const auditSign = (item, auditor_type, visa_date_type = 0) => {
	const data = {
		batch: item.batch,
		code: item.code,
		auditor_type,
		remark: item.remark,
	}
	postJson('visa/audit', data).then(data => {
		proxy.$message.success("签名成功", 1);
		if (visa_date_type === 1) {
			auditModel.visible = false;
		}
		initPage()
	}).catch(err => {
		proxy.$message.error(err);
	});
}
function back() {
	router.push('/yanshou/visaLX');
}
function saveHour() {
	let validateError = '';
	if (!formState.value.build_phase) {
		validateError = '请选择施工阶段';
	} else if (!formState.value.work_source_id) {
		validateError = '请选择工作事由';
	} else if (!formState.value.gonghao_id) {
		validateError = '请选择工作部位';
	} else if (!formState.value.work_time_list.filter(item => item.work_range?.length).length) {
		validateError = '请选择作业时间';
	} else if (!formState.value.work_hours) {
		validateError = '请输入累计完成时间';
	} else if (!formState.value.provider_id) {
		validateError = '请选择出工单位';
	} else if (formState.value.work_hours > Math.min(maxUseTime.value, 20)) {
		validateError = '累计完成时间不能超过预约的工作时长且不可超过20小时';
	}
	if (validateError) {
		proxy.$message.error(validateError);
		return;
	}
	const data = JSON.parse(JSON.stringify(formState.value));
	data.work_time_list = data.work_time_list.map(item => {
		if (item.work_range[0]) item.work_range[0] = dayjs(item.work_range[0]).format('YYYY-MM-DD HH:mm:00');
		if (item.work_range[1]) item.work_range[1] = dayjs(item.work_range[1]).format('YYYY-MM-DD HH:mm:00');
		return item;
	});
	data.gonghao_id = data.gonghao_id.split('-').slice(-1)[0];
	beingSubmitted.value = true;
	data.visa_type = 1;
	postJson('visa/save', data).then(data => {
		proxy.$message.success("保存成功", 1);
		beingSubmitted.value = false;
		closeTab("/yanshou/visaLX");
	}).catch(err => {
		proxy.$message.error(err);
		beingSubmitted.value = false;
	});
}

async function saveMonth(item) {
	let validateError = '';
	if (!item.start_time || !item.end_time) {
		validateError = '请选择工作时间段';
	} else if (!item.work_hours) {
		validateError = '请输入运转时间';
	} else if (!item.gonghao_id) {
		validateError = '请选择施工工号';
	} else if (!item.fuel_oil) {
		validateError = '请输入燃油';
	} else if (!formStateMonth.value.material_no) {
		validateError = '请输入设备编号';
	} else if (!formStateMonth.value.material_license_plate) {
		validateError = '请输入设备牌照';
	}
	// else if (formState.value.work_hours > Math.min(maxUseTime.value, 20)) {
	//   validateError = '累计完成时间不能超过预约的工作时长且不可超过20小时';
	// }
	if (validateError) {
		proxy.$message.error(validateError);
		return;
	}
	const data = JSON.parse(JSON.stringify(item));
	data.work_time_list = [{
		work_range: [
			dayjs(item.start_time).format(dayjs(data.visa_date).format('YYYY-MM-DD') + ' HH:mm:00'),
			dayjs(item.end_time).format(dayjs(data.visa_date).format('YYYY-MM-DD') + ' HH:mm:00'),
		]
	}];
	delete data.start_time;
	delete data.end_time;
	delete data.beingSubmitted;
	data.supply_order_id = id.value;
	data.code = supplyOrderInfo.value.visaLogs.find(item => dayjs(item.visa_date).format('YYYY-MM') === dayjs(data.visa_date).format('YYYY-MM'))?.code;
	if (!data.code) {
		const { code } = await postJson('visa/code', { supply_order_id: id.value, visa_date_type: 1, visa_date: data.visa_date });
		data.code = code;
	}
	data.gonghao_id = data.gonghao_id.split('-').slice(-1)[0];
	data.visa_date_type = formStateMonth.value.visa_date_type;
	data.material_no = formStateMonth.value.material_no;
	data.material_license_plate = formStateMonth.value.material_license_plate;
	item.beingSubmitted = true;
	data.visa_type = 1;
	postJson('visa/save', data).then(data => {
		proxy.$message.success("保存成功", 1);
		item.beingSubmitted = false;
		initPage()
	}).catch(err => {
		proxy.$message.error(err);
		item.beingSubmitted = false;
	});
}

const canAudit = () => {
	const visaLog = supplyOrderInfo.value.visaLogs?.find(item => item.code === formStateMonth.value.code);
	return visaLog && visaLog.visa_status !== 0 && dayjs().format('YYYY-MM') > dayjs(visaLog.visa_date).format('YYYY-MM');
}
const openAuditModel = (auditor_type) => {
	auditModel.visible = true;
	auditModel.data = {
		code: formStateMonth.value.code,
		batch: supplyOrderInfo.value.visaLogs.find(item => item.code === formStateMonth.value.code).batch,
		auditor_type,
		remark: ''
	}
}

const closeTab = inject("closeTab");
</script>
<style>
  .export {
    width: 1200px;
    text-align: right;
    margin: 0 auto;
  }
  .tab-page {
    width: 1200px;
    margin: 0 auto;
    font-size: 1rem;
    background-color: white;
    border-right: 1px solid rgba(0, 0, 0, 0.65);
    border-bottom: 1px solid rgba(0, 0, 0, 0.65);
    .ant-row {
      .ant-col {
        padding: 5px 5px 5px 10px;
        border-top: 1px solid rgba(0, 0, 0, 0.65);
        border-left: 1px solid rgba(0, 0, 0, 0.65);
      }
      .parent-col {
        div {
          height: 100%;
        }
        border: 0px;
        padding: 0px;
      }
      .parent-col-not-h-full {
        border: 0px;
        padding: 0px;
      }
    }
  }
  .upload-list-inline :deep(.ant-upload-list-item) {
    float: left;
    width: 200px;
    margin-right: 8px;
  }
  .upload-list-inline [class*='-upload-list-rtl'] :deep(.ant-upload-list-item) {
    float: right;
  }
</style>